# -*- coding: UTF-8 -*-
from PIL import Image, ImageTk
from tkinter import messagebox, ttk, filedialog
from tkinter.ttk import Frame
import handle_balance
import handle_benefit
import init_dict
import init_excel
import os
import pandas
import shutil
import time
import tkinter as tk


class Main(Frame):
    def __init__(self, master):
        super().__init__(master)
        self.general2subtitle = init_dict.general2subtitle
        # creat working directory
        try:
            os.mkdir('data')
            os.mkdir('data/records')
            # shutil.copyfile('balance', 'data/balance.xlsx')
            with open('data/balance.xlsx', 'wb') as f:
                f.write(
                    bytes.fromhex(init_excel.file_str)
                )
        except FileExistsError:
            pass

        handle_balance.update_balance_sheet()
        self.img_path = None
        # img frame
        self.img_frame = tk.Frame(master)
        self.img_frame.pack()
        self.img_label = tk.Label(self.img_frame)
        self.img_label.pack()

        # title frame
        self.title_frame = tk.Frame(master)
        self.title_frame.pack()
        # Date
        self.date_label = tk.Label(self.title_frame, text='日期')
        self.date_label.pack(side='left')
        self.date_var = tk.StringVar()
        self.date_var.set(time.asctime())
        self.date_entry = tk.Entry(
            self.title_frame, textvariable=self.date_var)
        self.date_entry.pack(side='left')

        self.summary_label = tk.Label(self.title_frame, text='摘要')
        self.summary_label.pack(side='left')
        self.summary_entry = tk.Entry(self.title_frame)
        self.summary_entry.pack(side='left')
        self.img_button = tk.Button(
            self.title_frame, text='上传图片', command=self.add_img)
        self.img_button.pack(side='left')

        self.borrow_group = tk.LabelFrame(master, text='借')
        self.borrow_group.pack()
        self.loan_group = tk.LabelFrame(master, text='贷')
        self.loan_group.pack()

        # lists for Frames of each lines
        self.borrow_frame_list = []
        self.loan_frame_list = []
        # lists for Recodes of each lines
        self.record_list = []
        # lists for general account comboboxes
        self.borrow_general_combobox_list = []
        self.loan_general_combobox_list = []
        # lists for subtitle comboboxes
        self.borrow_subtitle_combobox_list = []
        self.loan_subtitle_combobox_list = []
        # lists for Entries
        self.borrow_entry_list = []
        self.loan_entry_list = []

        # Generate the initial interface
        # Add button
        self.borrow_add_button = tk.Button(
            self.borrow_group, text='增加', command=self.borrow_add_button_func)
        self.borrow_add_button.pack(side='bottom')
        self.loan_add_button = tk.Button(
            self.loan_group, text='增加', command=self.loan_add_button_func)
        self.loan_add_button.pack(side='bottom')
        self.confirm_button = tk.Button(
            master, text='确认', command=self.confirm_button_func)
        self.confirm_button.pack()

        self.borrow_add_button_func()
        self.loan_add_button_func()

    def general_combobox_func(self, event):
        (self.borrow_group.nametowidget(event.widget.winfo_parent())).winfo_children()[
            1]['value'] = self.general2subtitle[event.widget.get()]

    def borrow_add_button_func(self):
        self.borrow_frame_list.append(tk.Frame(self.borrow_group))
        self.borrow_frame_list[-1].pack()
        self.borrow_general_combobox_list.append(ttk.Combobox(
            self.borrow_frame_list[-1], value=list(self.general2subtitle.keys())))
        self.borrow_general_combobox_list[-1].bind(
            '<<ComboboxSelected>>', self.general_combobox_func)
        self.borrow_general_combobox_list[-1].pack(side='left')
        self.borrow_subtitle_combobox_list.append(
            ttk.Combobox(self.borrow_frame_list[-1]))
        self.borrow_subtitle_combobox_list[-1].pack(side='left')
        self.borrow_entry_list.append(tk.Entry(self.borrow_frame_list[-1]))
        self.borrow_entry_list[-1].pack(side='left')

    def loan_add_button_func(self):
        self.loan_frame_list.append(tk.Frame(self.loan_group))
        self.loan_frame_list[-1].pack()
        self.loan_general_combobox_list.append(ttk.Combobox(
            self.loan_frame_list[-1], value=list(self.general2subtitle.keys())))
        self.loan_general_combobox_list[-1].bind(
            '<<ComboboxSelected>>', self.general_combobox_func)
        self.loan_general_combobox_list[-1].pack(side='left')
        self.loan_subtitle_combobox_list.append(
            ttk.Combobox(self.loan_frame_list[-1]))
        self.loan_subtitle_combobox_list[-1].pack(side='left')
        self.loan_entry_list.append(tk.Entry(self.loan_frame_list[-1]))
        self.loan_entry_list[-1].pack(side='left')

    def confirm_button_func(self):
        # #
        # self.update_balance()
        # #
        self.record_list.clear()
        borrow_sum = 0
        loan_sum = 0
        # for borrow group
        for frame in self.borrow_group.winfo_children():
            if type(frame) == tk.Frame:
                generate_name = frame.winfo_children()[0].get()
                subtitle_name = frame.winfo_children()[1].get()
                number = float(frame.winfo_children()[2].get())
                borrow_sum += number
                record = pandas.Series(
                    {'类型': '借', '总账科目': generate_name, '子科目': subtitle_name, '金额': number})
                self.record_list.append(record)
                for widget in frame.winfo_children():
                    widget.destroy()
                frame.destroy()

        # for loan group
        for frame in self.loan_group.winfo_children():
            if type(frame) == tk.Frame:
                generate_name = frame.winfo_children()[0].get()
                subtitle_name = frame.winfo_children()[1].get()
                number = float(frame.winfo_children()[2].get())
                loan_sum += number
                record = pandas.Series(
                    {'类型': '贷', '总账科目': generate_name, '子科目': subtitle_name, '金额': number})
                self.record_list.append(record)
                for widget in frame.winfo_children():
                    widget.destroy()
                frame.destroy()

        self.borrow_frame_list.clear()
        self.loan_frame_list.clear()
        self.borrow_add_button_func()
        self.loan_add_button_func()

        borrow_sum = round(borrow_sum, 2)
        loan_sum = round(loan_sum, 2)

        print('Borrow:', borrow_sum)
        print("Loan:", loan_sum)
        for record in self.record_list:
            print(record)
        self.date_var.set(time.asctime())
        if borrow_sum != loan_sum:
            messagebox.showerror(
                '错误', '借贷总和不一致, 借：{}, 贷：{}'.format(borrow_sum, loan_sum))
        # elif not self.img_path:
        #     messagebox.showerror('错误', '请插入图片')
        else:
            self.save()
            self.update_balance()
        self.img_label.destroy()
        self.img_path = None

        handle_balance.update_balance_sheet()
        handle_benefit.create()

    def add_img(self):
        self.img_path = filedialog.askopenfilename(
            filetypes=[("PNG", ".png"), ("GPF", ".gpf"), ("JPG", ".jpg")])
        img = Image.open(self.img_path)
        # resize img
        scale = img.height / 200
        img = img.resize((int(img.width / scale), 200))
        self.img = ImageTk.PhotoImage(img)
        self.img_label.destroy()
        self.img_label = tk.Label(self.img_frame, image=self.img)
        self.img_label.pack()

    def save(self):
        dir_name = 'data/records/'+self.date_entry.get().replace(':', '_')
        os.mkdir(dir_name)

        d = {index+1: record for (index, record)
             in enumerate(self.record_list)}
        frame = pandas.DataFrame(d).T

        # for summary
        summary = self.summary_entry.get()
        series = pandas.Series({'摘要': summary})
        frame = frame.append(series, ignore_index=True)

        frame.to_excel(dir_name + '/records.xlsx', index=False)
        # for image
        if self.img_path:
            postfix = self.img_path[self.img_path.rfind('.'):]
            shutil.copyfile(self.img_path, dir_name + '/img' + postfix)

    def update_balance(self):
        df = pandas.read_excel('data/balance.xlsx', index_col=0)
        for record in self.record_list:
            if record['类型'] == df['借/贷'][record['总账科目']]:
                df.at[record['总账科目'], '余额',
                      ] = df['余额'][record['总账科目']] + record['金额']
            else:
                df.at[record['总账科目'], '余额'] = df['余额'][record['总账科目']] - \
                    record['金额']
        df.to_excel('data/balance.xlsx', index=True)



if __name__ == "__main__":
    root = tk.Tk()
    root.title('银蛾')
    main = Main(root)
    main.mainloop()